<template>
  <view class="u-wrap">
    <view class="logo_fixed u-f-ajc">
      <image src="../../../static/images/huangjin/logo.png" mode="widthFix"></image>
    </view>
    <u-navbar title-color="#303133" :is-fixed="true" :is-back="false" :background="background"
      :back-text-style="{color: '#303133'}" :border-bottom="false">
      <view class="slot-wrap">
        <view class="search-wrap" @click="onSearch">
          <u-search v-model="keyword" :show-action="false" :height="70" :action-style="{color: '#fff'}"
            :border-color="'#fff'" :disabled="true"></u-search>
        </view>
      </view>
      <view class="navbar-right" slot="right" v-if="isMP" @click="onMine">
        <view class="message-box right-item">
          <u-icon name="dibutubiao_wode" custom-prefix="custom-icon"></u-icon>
        </view>
      </view>
    </u-navbar>
    <!-- <view class="top-warp">
      <u-tabs :list="categoryList" :name="'cat_name'" :current="tabIndex" bg-color="#FD5B00" active-color="#FFFFFF"
        inactive-color="#FFFFFF" @change="tabChangeHome"></u-tabs>
    </view> -->
    <view v-if="!tabIndex" class="contents">
      <view class="home-swiper-view">
        <view class="background-view"></view>
        <view class="home-swiper">
          <u-swiper :list="banner" :height="260" :border-radius="20" @click="blockHref"></u-swiper>
        </view>
        <view style="margin-top: 20rpx;">
          <u-notice-bar mode="vertical" :list="noticeList" @click="getArticleDetail"></u-notice-bar>
        </view>
        <!-- <image src="../../../static/images/huangjin/swiper.png" mode="widthFix" class="home-swiper"
          style="width: 100%;"></image> -->
        <view class="home-category">
          <!-- #ifdef APP-PLUS || H5 -->
          <navigator :url="menu.url" v-if="menu.url !== '/pages/live-video/live-video'" hover-class="none"
            class="category-item" v-for="(menu, menuIndex) in menus" :key="menuIndex">
            <u-image width="90rpx" height="90rpx" :src="menu.image"></u-image>
            <view class="menu-title">{{ menu.navigation_name }}</view>
          </navigator>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <navigator :url="menu.url" hover-class="none" class="category-item" v-for="(menu, menuIndex) in menus"
            :key="menuIndex">
            <u-image width="90rpx" height="90rpx" :src="menu.image"></u-image>
            <view class="menu-title">{{ menu.navigation_name }}</view>
          </navigator>
          <!-- #endif -->
        </view>
        <!-- <view class="noties relative"> -->
        <!-- <image src="../../../static/images/huangjin/noties.png" mode="widthFix" class="absolute"></image> -->
        <!-- <image src="../../../static/images/huangjin/kechengBanner.jpg" mode="widthFix" class="absolute"></image> -->
        <!-- <view class="wenan absolute u-f-ajc">
            <view style="margin-left: 90rpx;">今日金价:<text style="font-weight: 700;font-size: 48rpx;">￥511</text>/克</view>
          </view> -->
        <!-- </view> -->
      </view>
      <view class="block-view" v-if="time !== false && seckillGoodsList && seckillGoodsList.length">
        <view class="block-header">
          <view class="block-title u-flex">
            <view class="seckill-title">
              限时抢购
            </view>
            <view class="seckill-times">
              <text class="seckill-nth">{{timeLine.distance_time == 0 ? (onlyOne ? '距结束' : '距下轮开始') : '距开始'}}</text>
              <text class="seckill-time">{{ times.hours }}:{{ times.minutes }}:{{ times.seconds }}</text>
            </view>
          </view>
          <navigator url="/pages/seckill/seckill" hover-class="none" class="more-text">
            更多商品
            <u-icon class="u-margin-left-8" name="arrow-right" color="#333" size="27"></u-icon>
          </navigator>
        </view>
        <view class="goods-list-view">
          <scroll-view scroll-x style="white-space:nowrap;">
            <navigator :url="'/goods-module/goods?goods_id=' + goods.goods_id" hover-class="none" class="goods-item"
              v-for="(goods, index) in seckillGoodsList" :key="index">
              <view class="goods-img">
                <image class="img" :src="goods.goods_image"></image>
              </view>
              <custom-price :price="goods.seckill_price" :size="30" :fontWeight="600"></custom-price>
              <view class="original-price">
                <text>￥{{ goods.original_price }}</text>
              </view>
            </navigator>
          </scroll-view>
        </view>
      </view>
      <view v-if="floorList" class="floor-container">
        <view :class="'item-' + item.tpl_id" v-for="(item, itemIndex) in floorList" :key="itemIndex">
          <tpl23 v-if="item.tpl_id === 23" :item="item"></tpl23>
          <tpl24 v-if="item.tpl_id === 24" :item="item"></tpl24>
          <tpl25 v-if="item.tpl_id === 25" :item="item"></tpl25>
          <tpl26 v-if="item.tpl_id === 26" :item="item"></tpl26>
          <tpl27 v-if="item.tpl_id === 27" :item="item"></tpl27>
          <tpl28 v-if="item.tpl_id === 28" :item="item"></tpl28>
          <tpl29 v-if="item.tpl_id === 29" :item="item"></tpl29>
          <tpl30 v-if="item.tpl_id === 30 && itemIndex == 0" :item="item"
            @click.native="$u.route(`/goods-module/goods-list?category=1422023529783660545`)"></tpl30>
          <tpl30 v-if="item.tpl_id === 30 && itemIndex == 3" :item="item"
            @click.native="$u.route(`/goods-module/goods-list?category=1422023560179781633`)"></tpl30>
          <!-- <tpl30 v-if="item.tpl_id === 30" :item="item"></tpl30> -->
          <tpl31 v-if="item.tpl_id === 31" :item="item"></tpl31>
          <tpl32 v-if="item.tpl_id === 32" :item="item"></tpl32>
          <tpl37 v-if="item.tpl_id === 37" :item="item"></tpl37>
          <tpl38 v-if="item.tpl_id === 38" :item="item"></tpl38>
          <tpl42 v-if="item.tpl_id === 42" :item="item"></tpl42>
        </view>
      </view>
    </view>
    <mescroll-item ref="mescrollItem" v-for="(tab, i) in categoryList" :key="i" :i="i" :index="tabIndex"
      :tabs="categoryList"></mescroll-item>
    <u-no-network></u-no-network>
    
    <u-mask :show="showMask && !!popupImg" @click="showMask = false">
    		<view class="warp">
    			<!-- <view class="rect" @tap.stop></view> -->
          <view class="relative u-f-ajc" style="width: 100%;height: 100%;">
            <image :src="popupImg" mode="widthFix" style="width: 100%;"></image>
            <scroll-view class="absolute scroll_box" scroll-y>
              <view v-html="popupArticle.content"></view>
            </scroll-view>
          </view>
    		</view>
    	</u-mask>

    <app-update :app_show="app_show" :content='content' :url='url' :type="type" @updateShow="updateShow"></app-update>
  </view>
</template>

<script>
  import {
    getUrlParam,
    getCodeApi,
    isWeixin
  } from '@/utils/wx.js'

  import * as API_Home from '@/api/home.js'
  import * as API_Goods from '@/api/goods.js'
  import * as API_Common from '@/api/common.js'
  import * as API_Promotions from '@/api/promotions.js'
  import * as Openid from '@/api/openid.js'
  import * as API_Article from '@/api/article.js';
  import {
    Foundation
  } from '@/ui-utils/index.js'
  import Cache, {
    Keys
  } from '@/utils/cache.js'
  import tpl23 from './templates/tpl_23.vue'
  import tpl24 from './templates/tpl_24.vue'
  import tpl25 from './templates/tpl_25.vue'
  import tpl26 from './templates/tpl_26.vue'
  import tpl27 from './templates/tpl_27.vue'
  import tpl28 from './templates/tpl_28.vue'
  import tpl29 from './templates/tpl_29.vue'
  import tpl30 from './templates/tpl_30.vue'
  import tpl31 from './templates/tpl_31.vue'
  import tpl32 from './templates/tpl_32.vue'
  import tpl37 from './templates/tpl_37.vue'
  import tpl38 from './templates/tpl_38.vue'
  import tpl42 from './templates/tpl_42.vue'
  import MescrollItem from "./mescroll-item.vue"
  import AppUpdate from '@/components/AppUpdate/AppUpdate.vue';
  import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js"

  export default {
    components: {
      tpl23,
      tpl24,
      tpl25,
      tpl26,
      tpl27,
      tpl28,
      tpl29,
      tpl30,
      tpl31,
      tpl32,
      tpl37,
      tpl38,
      tpl42,
      MescrollItem,
      AppUpdate,
    },
    mixins: [MescrollMoreMixin],
    data() {
      return {
        noticeList: [],
        noticeListId: [],

        keyword: '',
        //如果是小程序则隐藏
        // #ifdef MP
        isMP: false,
        background: {
          background: '#FD5B00'
        },
        // #endif
        //如果是不是小程序则展示
        // #ifndef MP
        isMP: true,
        background: {
          background: 'url(../../../static/images/bg/bg2.png) no-repeat',
          backgroundSize: 'cover'
        },
        // #endif
        tabIndex: 0,
        categoryList: [], //分类数据
        time: false, //时间
        // 时间
        times: {
          hours: '00',
          minutes: '00',
          seconds: '00'
        },
        timeLine: '', //当前这一场的时刻信息
        onlyOne: false, //是否只有一场
        seckillGoodsList: [], //限时抢购商品列表
        goodsList: [], //商品列表
        banner: [], //轮播图
        menus: [], //菜单栏
        floorList: [], //楼层数据
        networkType: '', //网络状态

        app_show: false,
        content: '',
        type: '',
        url: '',
        strTime: 0,
        
        popupImg: '',
        showMask: true,
        popupArticle: {},
      };
    },
    async onLoad() {
      // // #ifdef H5
      // if (isWeixin()) {
      //   // uni.setStorageSync('OpenId','ooOZmwf2CxWivdjQL4_3_DqA4Q7s')
      //   let localOpenId = uni.getStorageSync("openid");
      //   console.log('openid', localOpenId)
      //   if (!localOpenId) {
      //     this.getCode();
      //   }
      // }
      // // #endif

      let $this = this
      //获取网络类型
      uni.getNetworkType({
        success(res) {
          $this.networkType = res.networkType
          if (res.networkType !== 'none') {
            $this.init()
          }
        }
      })
    },
    onShow() {
      this.getArticle()
      let $this = this
      //监听网络状态变化
      uni.onNetworkStatusChange(res => {
        //监听到有网络并且第一次没有加载数据的情况下初始化数据
        if (res.isConnected && $this.networkType === 'none') {
          $this.init()
        }
      })
    },
    // onBackPress() {
    //   let strTime = new Date().getTime()
    //   if (strTime - this.strTime <= 2000) {
    //     console.log('连续两次返回 就是退出')
    //     this.onLogout()
    //   }
    //   this.strTime = strTime
    // },
    methods: {
      async getArticle() {
        this.showMask = true
        let res = await API_Article.getArticleDetail(100)
        console.log(res)
        this.popupArticle = res
      },
      async getArticlesByCategory() {
        let res = await API_Article.getArticlesByCategory('NOTICE')
        console.log('查看所有商城分类文章', res)
        if (res && res.length) {
          this.noticeList = res.map(item => item.article_name)
          this.noticeListId = res
        }
      },
      getArticleDetail(index) {
        console.log(index)
        let id = this.noticeListId[index].article_id
        this.$u.route(`/mine-module/about_us?id=${id}`)
      },
      
      getCode() {
        const code = getUrlParam("code");
        console.log('查看code', code)
        if (code == null || code === "") {
          let localOpenId = uni.getStorageSync("openid");
          if (!localOpenId) {
            getCodeApi();
          }
        } else {
          this.getOpenId(code);
        }
      },
      getOpenId(code) {
        Openid.fetchWeiXinH5OpenId(code).then(openid => {
          uni.setStorageSync('openid', openid)
        })
      },
      //退出登录
      onLogout() {
        uni.$emit('logout', {
          msg: '退出登录消息'
        })
        let mobile = uni.getStorageSync('mobile')
        //清除会员信息
        uni.removeStorageSync('user')
        //清除token
        uni.removeStorageSync('accessToken')
        uni.setStorageSync('mobile', mobile)
      },
      async getVersion() {
        let _this = this;
        let res = await API_Common.getwapVersion()
        console.log('查看服务器app版本:', res)
        plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
          // 资源包替换更新
          if (widgetInfo.version != res) {
            _this.app_show = true;
            // _this.content = '点击按钮复制链接到浏览器打开下载新版本';
            _this.content = '点击按钮下载最新版本~';
            // _this.url = 'res.wgturl';
            _this.url = 'http://xingruiappdownload.oss-cn-beijing.aliyuncs.com/xingbaihui.apk';
            if (uni.getSystemInfoSync().platform === 'ios') {
              _this.url = 'https://www.lanzoui.com/xingruizhubao';
            }
            _this.type = '2';
            uni.hideTabBar();
          }
        });
      },
      updateShow() {
        this.app_show = false
        uni.showTabBar()
      },
      async init() {
        // #ifdef APP-PLUS
        this.getVersion();
        // #endif
        this.getArticlesByCategory()
        const values = await Promise.all([
          API_Home.getFocusPictures('WAP'),
          API_Home.getSiteMenu('MOBILE'),
          API_Home.getFloorData('WAP'),
          API_Goods.getCategory(),
          API_Common.getSiteData()
        ])
        
        this.popupImg = values[4].default_img
        
        const _banner = values[0].map(item => {
          item.image = item.pic_url
          return item
        })
        const page_data = values[2].page_data ? JSON.parse(values[2].page_data) : []
        this.banner = _banner
        //菜单栏(支持跳转到商品详情页)
        // values[1].forEach(item => {
        //   if (/^\/goods\/.*/.test(item.url)) {
        //     item.url = item.url.replace('/goods/', '/goods-module/goods?goods_id=')
        //   } else {
        //     item.url = `/pages${item.url}${item.url}`
        //   }
        // })
        this.menus = values[1]
        this.floorList = page_data
        console.log('查看楼层', this.floorList)
        //小程序发布需过滤医药及食品类目
        // const _categoryList = values[3].filter(key=> key.category_id != 85 && key.category_id != 4)
        this.categoryList = values[3]
        this.categoryList.unshift({
          name: '首页',
          category_id: ''
        })
        Cache.setItem(Keys.site, values[4])
        this.getTimeline()
      },
      //获取时间段
      getTimeline() {
        API_Promotions.getSeckillTimeLine().then(response => {
          const data = response
          if (!data || !data.length) return
          const res = data.sort((x, y) => (Number(x.time_text) - Number(y.time_text)))
          const onlyOne = res.length === 1
          this.onlyOne = onlyOne
          this.time = res[0].distance_time != 0 ? res[0].distance_time : onlyOne ? Foundation.theNextDayTime() :
            res[1].distance_time
          this.timeLine = res[0]
          this.startCountDown()
          this.getSeckillTimeGoods(res[0].time_text)
        })
      },
      //开始倒计时
      startCountDown() {
        this.interval = setInterval(() => {
          let {
            time
          } = this
          if (time <= 0) {
            clearInterval(this.interval)
            if (this.onlyOne) {
              uni.showModal({
                title: '提示',
                showCancel: false,
                confirmColor: "#FD5B00",
                content: '本轮限时抢购已结束！',
                success(res) {
                  uni.reLaunch({
                    url: '/pages/tabs/home/home'
                  })
                }
              })
            } else {
              uni.showModal({
                title: '提示',
                showCancel: false,
                confirmColor: "#FD5B00",
                content: '下一轮限时抢购已经开始啦！请确认查看',
                success(res) {
                  uni.reLaunch({
                    url: '/pages/tabs/home/home'
                  })
                }
              })
            }
            return false
          }
          this.time -= 1
          this.times = Foundation.countTimeDown(time)
        }, 1000)
      },
      //获取时间段商品
      getSeckillTimeGoods(range_time) {
        API_Promotions.getSeckillTimeGoods({
          range_time
        }).then(response => {
          const {
            data
          } = response
          this.seckillGoodsList = data
        })
      },
      // 轮播图点击事件
      blockHref(index) {
        const {
          operation_type,
          operation_param
        } = this.banner[index]
        switch (operation_type) {
          // 链接地址
          case 'URL':
            uni.navigateTo({
              url: `/pages${operation_param}${operation_param}`
            })
            break
            // 商品
          case 'GOODS':
            uni.navigateTo({
              url: `/goods-module/goods?goods_id=${operation_param}`
            })
            break
            // 关键字
          case 'KEYWORD':
            uni.navigateTo({
              url: `/goods-module/goods-list?keyword=${operation_param}`
            })
            break
            // 店铺
          case 'SHOP':
            uni.navigateTo({
              url: `/pages/shop/shop?shop_id=${operation_param}`
            })
            break
            // 分类
          case 'CATEGORY':
            uni.navigateTo({
              url: `/goods-module/goods-list?category=${operation_param}`
            })
            break
        }
      },
      //搜索
      onSearch() {
        uni.navigateTo({
          url: '/pages/search/search'
        })
      },
      //我的
      onMine() {
        uni.switchTab({
          url: '/pages/tabs/mine/mine'
        })
      },
      //导航栏点击
      tabChangeHome(index) {
        this.tabIndex = index
      }
    }
  }
</script>

<style lang="scss" scoped>
  .top-warp {
    z-index: 9990;
    position: fixed;
    // top: --window-top;
    top: 200rpx;
    /* css变量 */
    left: 0;
    width: 100%;
    background-color: $u-type-error;
  }

  .slot-wrap {
    flex: 1;
    padding-left: 20rpx;

    .search-wrap {
      margin: 0 20rpx;
    }
  }

  .navbar-right {
    color: #FFFFFF;
    margin-right: 24rpx;
    display: flex;

    .right-item {
      position: relative;
      color: #FFFFFF;
      display: flex;
      font-size: 40rpx;
      font-weight: 600;
    }
  }

  .home-swiper-view {
    .background-view {
      background-color: $u-type-error;
      height: 200rpx;
      border-bottom-right-radius: 4em 0.2em;
      border-bottom-left-radius: 4em 0.2em;
    }

    .home-swiper {
      // margin: 0rpx 30rpx;
      margin-top: -180rpx;
      box-shadow: 0px 20rpx 10rpx -10rpx #c0c4cc;
    }

    .home-category {
      // margin: 20rpx 30rpx;
      margin: 10rpx 30rpx 20rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      flex-wrap: wrap;

      .category-item {
        display: flex;
        align-items: center;
        flex-direction: column;
        width: 25%;
        margin-top: 20rpx;

        .menu-title {
          margin-top: 10rpx;
          font-size: 26rpx;
        }
      }
    }
  }

  .floor-container {
    margin: 10rpx 20rpx 20rpx 20rpx;
    border-radius: 10rpx;
    overflow: hidden;
  }

  .block-view {
    background-color: #fff;
    margin: 10rpx 20rpx 20rpx 20rpx;
    border-radius: 10rpx;
    padding: 10rpx 15rpx;

    .block-header {
      font-size: 31rpx;
      padding: 20rpx 0rpx;
      display: flex;
      align-items: center;
      flex-direction: row;
      justify-content: space-between;

      .seckill-title {
        font-weight: 600;
        font-size: 34rpx;
      }

      .seckill-times {
        margin: 0 20rpx;
        font-size: 22rpx;

        .seckill-nth {
          color: #fff;
          padding: 4rpx 10rpx;
          border-top-left-radius: 30rpx;
          border-bottom-left-radius: 30rpx;
          background-color: #FD5B00;
          border: 2rpx solid #FD5B00;
        }

        .seckill-time {
          color: #FD5B00;
          font-weight: 600;
          padding: 4rpx 10rpx;
          border-top-right-radius: 30rpx;
          border-bottom-right-radius: 30rpx;
          border: 2rpx solid #FD5B00;
        }
      }

      .more-text {
        color: #909399;
        font-size: 25rpx;
      }
    }

    .goods-list-view {
      .goods-item {
        width: 20%;
        display: inline-block;
        background: #fff;
        margin: 8rpx;
        border-radius: 10rpx;
        text-align: center;

        .goods-img {
          width: 120rpx;
          height: 120rpx;

          .img {
            width: 100%;
            height: 100%;
          }
        }

        .original-price {
          color: #ABABAB;
          font-size: 22rpx;
          line-height: 24rpx;
          margin-bottom: 15rpx;
          padding: 0 4rpx;
          text-decoration: line-through;
        }
      }
    }
  }

  .logo_fixed {
    width: 100%;
    height: 150rpx;
    background-color: #F04531;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 999;

    image {
      width: 500rpx;
      margin-top: 50rpx;
      /*  #ifdef  APP-PLUS  */
      margin-top: 120rpx;
      /*  #endif  */
    }
  }

  .noties {
    font-size: 32rpx;
    width: 100%;
    height: 220rpx;
    color: #FFFFFF;

    image {
      width: 100%;
      padding: 0 20rpx;
      box-sizing: border-box;
    }

    .wenan {
      width: 100%;
      height: 100%;
    }
  }

  /deep/ .u-navbar-fixed {
    top: 150rpx !important;
    /*  #ifdef  APP-PLUS  */
    top: 120rpx !important;
    /*  #endif  */
  }

  .contents {
    margin-top: 150rpx;
    padding-bottom: 100rpx;
    /*  #ifdef  APP-PLUS  */
    margin-top: 120rpx;
    /*  #endif  */
  }
  
  	.warp {
  		display: flex;
  		align-items: center;
  		justify-content: center;
  		height: 100%;
  	}
  
  	.rect {
  		width: 120px;
  		height: 120px;
  		background-color: #fff;
  	}
    
    .scroll_box {
      width: 75%;
      height: 580rpx;
      margin-top: 190rpx;
      // background-color: skyblue;
    }
</style>
